﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Ninject;
using SydEnergiPrototype.Logic;
using SydEnergiPrototype.Model;

namespace SydEnergiPrototype.DataAccess
{
    public class ChangeAddressDataService : Subject, IDataService
    {
        public void RetrieveCabinets(ReturnResult callback)
        {
            _dataService.RetrieveCabinets(callback);
        }

        public void PersistEntry(ReturnResult callback)
        {
            if (callback.Parameter != null && callback.Parameter.EntryAddress.GetType() == typeof (MarkedAddress))
            {
                _dataRepository.GetCabinetsAsync(new ReturnResult(GetCabinetsCompleted, callback.Parameter));
            }
            else
            {
                _dataService.PersistEntry(callback);
            }
        }

        public void GetCabinetsCompleted(ReturnResult result)
        {
            var entry = result.Parameter;
            var cabinets = result.Result;

            var originalAddress = ((MarkedAddress)entry.EntryAddress).OriginalAddress;
            var alteredAddress = ((MarkedAddress)entry.EntryAddress).AlteredAddress;

            entry.EntryAddress = originalAddress;

            var cabinet = cabinets.Single(c => c.Id == entry.CabinetId);
            if (cabinet.EntryCollection.Any(c => c.EntryAddress.Equals(originalAddress)))
            {
                var i = cabinet.EntryCollection.IndexOf(entry);
                entry.EntryAddress = alteredAddress;
                cabinet.EntryCollection[i] = entry;
                _dataRepository.SetCabinetsAsync(NotifyObservers, cabinets);
            }
        }

        private readonly IDataService _dataService;
        private readonly IDataRepository _dataRepository;

        [Inject]
        public ChangeAddressDataService(IDataService dataService, IDataRepository dataRepository)
        {
            if(dataService == null)
                throw new ArgumentNullException("dataService");
            _dataService = dataService;

            if(dataRepository == null)
                throw  new ArgumentNullException("dataRepository");
            _dataRepository = dataRepository;
        }
    }
}
